package com.cysion.study.ui.login

import android.os.CountDownTimer
import android.view.View
import android.widget.CompoundButton
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.other._setOnClickListener
import com.cysion.other.color
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.R
import com.cysion.study.constant.BUNDLE_KEY
import com.cysion.study.constant.LOGIN_IN
import com.cysion.study.event.UserEvent
import com.cysion.study.helper.UserCache
import com.cysion.study.net.ApiClient
import com.cysion.study.widget.ShowToast
import kotlinx.android.synthetic.main.activity_forget.*
import kotlinx.android.synthetic.main.activity_forget.cb_private
import kotlinx.android.synthetic.main.activity_forget.cb_teacher
import kotlinx.android.synthetic.main.activity_forget.etCode
import kotlinx.android.synthetic.main.activity_forget.etPwd
import kotlinx.android.synthetic.main.activity_forget.etPwd2
import kotlinx.android.synthetic.main.activity_forget.etUsername
import kotlinx.android.synthetic.main.activity_forget.tvCode
import kotlinx.android.synthetic.main.activity_forget.tvLogin
import kotlinx.android.synthetic.main.activity_register.*
import org.greenrobot.eventbus.EventBus

/**
 * Created by chu on 2019-06-29.
 */
class ForgetPwdActivity:BaseActivity(), CompoundButton.OnCheckedChangeListener {
    private lateinit var pageType:String
    override fun getLayoutId(): Int {
        return R.layout.activity_forget
    }
    private lateinit var countTimer: CountTime
    var teacherType:String="0"
    override fun initView() {
        darkTextTheme(color(R.color.main_cl))

        val bundleExtra=intent.getBundleExtra(BUNDLE_KEY)
        //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码
        // 5、绑定手机号码 6、提现银行卡绑定 7、家教老师H5推广注册
        pageType = bundleExtra.getString("pageType")
        countTimer = CountTime(60000, 1000)
        topbar.apply {
          if (pageType == "2") {
//                ll_teacher_type.visibility = View.GONE
                setTitle("设置支付密码")
            }else if (pageType == "1") {
//                ll_teacher_type.visibility = View.GONE
                setTitle("修改登录密码")
            }
//            setImageRes(R.mipmap.icon_back,TopBar.Pos.LEFT)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        cb_teacher.setOnCheckedChangeListener(this)
        cb_private.setOnCheckedChangeListener(this)

        tvCode._setOnClickListener {
            etUsername.checkBlank("手机号不能为空") ?: return@_setOnClickListener
            Alert.loading(self)
            //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码

            ApiClient.api.sendCdoe(etUsername.text.toString().trim(),pageType).compose(BaseResponseRx.validateToMain())
                ._subscribe {
                    _onNext {
                        Alert.close()
                        ShowToast("发送成功")
                    }
                    _onError {
                        Alert.close()
                        val handle= ErrorHandler.handle(it)
                        ShowToast(handle.errorMsg)
                        if (countTimer != null) {
                            countTimer.cancel()
                        }
                        tvCode.isEnabled = true
                        tvCode.text = "获取验证码"

                    }
                }
            countTimer.start()
            tvCode.isEnabled = false
        }

        tvLogin._setOnClickListener {
            val account = etUsername.text.toString().trim()
            val pwd = etPwd.text.toString().trim()
            val code = etCode.text.toString().trim()
            etUsername.checkBlank("手机号不能为空") ?: return@_setOnClickListener
            etCode.checkBlank("验证码不能为空") ?: return@_setOnClickListener
            etPwd.checkBlank("密码不能为空") ?: return@_setOnClickListener
            etPwd2.checkBlank("密码不能为空") ?: return@_setOnClickListener

            if (etUsername.text.toString().length < 11 || etPwd.text.length < 6) {
                ShowToast("请输入正确的手机号或6位以上密码")
                return@_setOnClickListener
            }
            if (etPwd.text.toString() != etPwd2.text.toString()) {
                ShowToast("两次输入密码不一致")
                return@_setOnClickListener
            }
            //登录类型 1.普通员工 2.私教
            if (cb_teacher.isChecked) {
                teacherType = "1"
            } else if (cb_private.isChecked) {
                teacherType = "2"
            }
            Alert.loading(self)
            //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码
            ApiClient.api.checkCode(etUsername.text.toString().trim(), pageType, etCode.text.toString().trim())
                .compose(BaseResponseRx.validateToMain())
                ._subscribe {
                    _onNext {
                        Alert.close()
                        //验证码校验成功
                     if (pageType == "2") {//2设置支付密码
                            resetPayPwd()//2设置支付密码
                        }else if (pageType == "1") {//找回密码页面类型
                            resetPwd()//修改登录密码
                        }

                    }
                    _onError {
                        Alert.close()
                        val handle = ErrorHandler.handle(it)
                        ShowToast(handle.errorMsg)
                    }
                }
        }
    }
    inner class CountTime : CountDownTimer {
        constructor(millisInFuture: Long, countDownInterval: Long) : super(millisInFuture, countDownInterval)
        override fun onFinish() {
            tvCode.isEnabled = true
            tvCode.text = "获取验证码"
        }

        override fun onTick(millisUntilFinished: Long) {
            tvCode.text = "${millisUntilFinished/1000}秒"
        }

    }
    private fun resetPwd() {
        //账号类型 0.普通教师 1.私教
        ApiClient.api.resetLogin(etUsername.text.toString().trim(),etPwd.text.toString().trim(),etCode.text.toString().trim()).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("重置成功")
                    CLog.i("token=${it.token}")
                    ACache.get(Box.context).put("token", it.token)

                    finish()
                    EventBus.getDefault().post(UserEvent(LOGIN_IN, ""))
                }
                _onError {
                    Alert.close()
                    val handle= ErrorHandler.handle(it)
                    ShowToast(handle.errorMsg)
                }
            }
    }

    private fun resetPayPwd() {
        ApiClient.api.setPayPassword(etPwd.text.toString().trim(),etCode.text.toString().trim(), UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("重置成功")
                    finish()
                }
                _onError {
                    Alert.close()
                    val handle= ErrorHandler.handle(it)
                    ShowToast(handle.errorMsg)
                }
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countTimer != null) {
            countTimer.cancel()
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        if (buttonView != null) {
            if (buttonView.id == cb_teacher.id) {
                cb_private.isChecked = !isChecked
            } else if (buttonView.id == cb_private.id) {
                cb_teacher.isChecked = !isChecked
            }
        }
    }

    override fun closeMvp() {
    }
}